import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import java.text.SimpleDateFormat
import java.text.DateFormat

class ChemSimilarityService  implements ApplicationContextAware {

  //the application context
  ApplicationContext applicationContext

  //needed for url generation
  def g = new org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib()

  File imageDir = null

  boolean transactional = false

  /**
   * create a .sif file given dataList
   * @param dataList
   * @param fileName
   * @return path to the file location
   */
  String createOutputFile(ArrayList dataList, String fileName) {

    imageDir = getApplicationContext().getResource("/outputFiles").getFile()
    String mainDir = "/" + imageDir.getName()

    // Used for unique file name creation
    DateFormat dateFormat = new SimpleDateFormat ("MMddyyyy");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);

    dateFormat = new SimpleDateFormat ("HHmmss");
    dateStr = dateStr + "_" +dateFormat.format (date);

    String name = fileName+"_"+dateStr+".sif";

//    println "mainDir :: ${mainDir}"
//    println "imageDir :: ${imageDir}"

    String finalName = g.createLinkTo(dir: mainDir, file: name)

//    println "finalName :: ${finalName}"

    File outputFile = new File(imageDir, name);

    Writer output = null;
    output = new BufferedWriter(new FileWriter(outputFile));

    for (int index=0 ; index < dataList.size() ; index++)
    {
      if(index==0)
      {
        output.write(dataList.get(index).toString().trim());
      }else
      {
        output.write("\n"+dataList.get(index).toString().trim());
      }
    }

    output.close();
    return finalName
  }
}
